package io.github.center.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.LinkedList;
import java.util.List;

/**
 * satoken自动装配类，权限校验
 *
 * @author haijun
 * @version 1.0.0
 * @email "1424132610@qq.com"
 * @date 2024.10.30 21:28
 * @since 1.0.0
 */
@Configuration
@AllArgsConstructor
@ConditionalOnProperty(prefix = ApplicationProperties.PREFIX, name = "auth.enable", havingValue = "true", matchIfMissing = true)
public class SaTokenAutoConfiguration implements WebMvcConfigurer {

    /**
     * 系统忽略路径
     */
    public static final List<String> SYSTEM_IGNORES = new LinkedList<String>();

    static {
        SYSTEM_IGNORES.add("/login/**");
        SYSTEM_IGNORES.add("/doc.html");
        SYSTEM_IGNORES.add("/v2/**");
        SYSTEM_IGNORES.add("/webjars/**");
        SYSTEM_IGNORES.add("/static/**");
        SYSTEM_IGNORES.add("/resources/**");
        SYSTEM_IGNORES.add("/swagger-resources");
        SYSTEM_IGNORES.add("/error");
    }

    /**
     * Application properties
     */
    private final ApplicationProperties applicationProperties;

    /**
     * 添加satoken拦截器相关信息
     *
     * @param registry registry
     * @since 1.0.0
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        ApplicationProperties.Auth auth = this.applicationProperties.getAuth();
        List<String> ignores = auth.getIgnores();
        if (CollectionUtil.isNotEmpty(ignores)) {
            SYSTEM_IGNORES.addAll(ignores);
        }
        registry.addInterceptor(new SaInterceptor(handler -> StpUtil.checkLogin()))
                .addPathPatterns("/**")
                .excludePathPatterns(SYSTEM_IGNORES);
    }
}
